package com.bootcamp.s3_1013.database._1019_JBUtils;

import com.bootcamp.s3_1013.database.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * @program: myClassCode
 * @description: query runner
 * @author: Keyu Li
 * @create: 2021-10-19 14:38
 **/

public class Demo3_ResultSetHandler {
    public static void main(String[] args) {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        beanHandlerDemo(queryRunner);
//        columnListHandlerDemo(queryRunner);    //把单列值封装为list
//        beanListHandlerDemo(queryRunner);      //封装为对象集合
//        scalarHandlerDemo(queryRunner);        //返回单个值
//        mapHandlerDemo(queryRunner);           //封装一行记录
//        mapListHandlerDemo(queryRunner);           //封装一行记录
    }

    private static void beanHandlerDemo(QueryRunner queryRunner) {
        try {
            City queryCity = queryRunner.query("select * from city where id=?", new BeanHandler<>(City.class), 1);
            System.out.println(queryCity);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    private static void mapListHandlerDemo(QueryRunner queryRunner) {
        try {
            List<Map<String, Object>> queryMapList = queryRunner.query("select * from city", new MapListHandler());
            System.out.println(queryMapList);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    private static void mapHandlerDemo(QueryRunner queryRunner) {
        try {
            Map<String, Object> queryMap = queryRunner.query("select * from city where id=?", new MapHandler(), 2);
            System.out.println(queryMap);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    private static void columnListHandlerDemo(QueryRunner queryRunner) {
        try {
//            City city = queryRunner.query("select * from city where id=?", new BeanHandler<>(City.class), 1);
            List<Object> list = queryRunner.query("select name from city", new ColumnListHandler<>());
            System.out.println(list);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

